// Package api 的活动模块：提供创建、列表、状态更新（启用/禁用）与删除接口。
package api

import (
	"encoding/json"
	"net/http"
	"strconv"
	"time"

	"github.com/we-pay-kit/we-pay-kit/internal/db"
	"github.com/we-pay-kit/we-pay-kit/internal/domain"
	"github.com/we-pay-kit/we-pay-kit/internal/repository"
)

type ActivityHandler struct {
	repo *repository.ActivityRepository
}

func NewActivityHandler() *ActivityHandler {
	return &ActivityHandler{repo: repository.NewActivityRepository(db.GetDB())}
}

// POST /api/v1/activities
func (h *ActivityHandler) CreateActivity(w http.ResponseWriter, r *http.Request) {
	var in struct {
		ActivityName    string  `json:"activity_name"`
		ActivityType    string  `json:"activity_type"`
		StartTime       string  `json:"start_time"`
		EndTime         string  `json:"end_time"`
		TotalBudget     float64 `json:"total_budget"`
		SingleMaxAmount float64 `json:"single_max_amount"`
		SingleMinAmount float64 `json:"single_min_amount"`
		RuleConfig      string  `json:"rule_config"`
		CreatedBy       string  `json:"created_by"`
	}
	if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	st, err := time.Parse(time.RFC3339, in.StartTime)
	if err != nil {
		http.Error(w, "invalid start_time", http.StatusBadRequest)
		return
	}
	et, err := time.Parse(time.RFC3339, in.EndTime)
	if err != nil {
		http.Error(w, "invalid end_time", http.StatusBadRequest)
		return
	}
	normalizedRule, err := domain.ValidateAndNormalize(in.ActivityType, in.RuleConfig)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	a := &repository.ActivityConfig{
		ActivityName:    in.ActivityName,
		ActivityType:    in.ActivityType,
		StartTime:       st,
		EndTime:         et,
		TotalBudget:     in.TotalBudget,
		SingleMaxAmount: in.SingleMaxAmount,
		SingleMinAmount: in.SingleMinAmount,
		RuleConfig:      normalizedRule,
		Status:          "DRAFT",
		CreatedBy:       in.CreatedBy,
	}
	id, err := h.repo.Create(r.Context(), a)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(map[string]any{"id": id})
}

// GET /api/v1/activities
func (h *ActivityHandler) ListActivities(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()
	limit, _ := strconv.Atoi(q.Get("limit"))
	offset, _ := strconv.Atoi(q.Get("offset"))
	list, err := h.repo.List(r.Context(), limit, offset)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(list)
}

// PATCH /api/v1/activities/status?id=1&status=ENABLED&updated_by=xxx
func (h *ActivityHandler) UpdateStatus(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()
	id, _ := strconv.ParseInt(q.Get("id"), 10, 64)
	status := q.Get("status")
	updatedBy := q.Get("updated_by")
	if id == 0 || status == "" || updatedBy == "" {
		http.Error(w, "missing params", http.StatusBadRequest)
		return
	}
	if err := h.repo.UpdateStatus(r.Context(), id, status, updatedBy); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

// DELETE /api/v1/activities?id=1
func (h *ActivityHandler) DeleteActivity(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()
	id, _ := strconv.ParseInt(q.Get("id"), 10, 64)
	if id == 0 {
		http.Error(w, "missing id", http.StatusBadRequest)
		return
	}
	if err := h.repo.Delete(r.Context(), id); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}
